(function($) {
	
	$.fn.isRegister = function() {

		return $(this).each(function(){

			var submited = false,
				$regContent = $('#reg_content'),
				$regError = $('#reg_error'),
				$regInfo = $('#reg_info'),
				$regAvatar = $('#reg_avatar'),
				$sysAvatarWrap = $('#sys_avatar_wrap');
			
			//用户上传头像
			$('#avatar_upload').file(function(inp) {
				
				$('#avatar').remove();
				inp.id = inp.name = 'avatar';
				$('#uploadForm').append(inp);
				
				$('#uploadForm').hide();
				$('#avatar_upload').hide();
				$('#uploading_text').show();
				
				$('#uploadForm').ajaxSubmit({
					async		: false,
					url			: $('#uploadForm').attr('action'), 
					type		: 'post',
					dataType	: 'xml',
					beforeSend	: function(xhr) {
						 xhr.setRequestHeader("X-Requested-With", "XMLHttpRequest");
					},
					success		: function(responseXML) {
						if($('success', responseXML).text() === 'true') {
							var avatarPath = [duobei.avatarPath, '/', $('avatarName', responseXML).text()].join(''),
								avatarId = $('avatarId', responseXML).text();
								
							$('#reg_avatar img').attr('src', avatarPath);
							$('#reg_avatar input').val(avatarId);
							
							$('#uploading_text').hide();
							$('#avatar_upload').show();
							
						} else {

							$('#uploading_text').hide();
							$('#avatar_upload').show();
							
//							$('#avatar_tip').slideDown();
							$('#avatar_tip').show();
						}
						return false;
					}
				});
			});
			
			$('.avatar_opr').toggle();

			$.validator.addMethod("duobeiValidEmail", function(value, element) {
		    	return this.optional(element) || /^(?:[a-zA-Z0-9]+[_\-\+\.]?)*[a-zA-Z0-9]+@(?:([a-zA-Z0-9]+[_\-]?)*[a-zA-Z0-9]+\.)+([a-zA-Z]{2,})+$/.test(value);
		    }, '邮箱的格式为email@example.com');
			
			$.validator.addMethod("duobeiNickname", function(value, element, param) {
				var str = value.replace(/[^\x00-\xff]/g, '**').replace(/\s+/g, ""), length = str.length,//把中文替换为两个半角字符，计算长度
				  	regexpNoWhiteSpace = /^\S+$/i,//空格
				  	validChar = /^[a-zA-Z0-9_\-\u4e00-\u9fa5]+$/,//中英文、数字、下划线、减号
				  	SBCcase=/[\uFE30-\uFFA0]/i, //匹配全角
			        result = (regexpNoWhiteSpace.test(value) && length >= param[0] && length <= param[1] && validChar.test(value) && (!SBCcase.test(value)));
			    
				return result;
			}, '名字应为2-15个汉字，或4-30个字母');
			
			$('#reg_form').validate({
				errorElement:'span',
				errorClass:'error',
				focusInvalid:true,
				onfocusout:false,
				onclick:false,
				onkeyup:false,
				submitHandler: function(form){
					if(!submited){
						submited = true;
						form.submit();
					}	
				},
				errorPlacement:function(error,element) {
					$('.error_wrap', $regError).append(error).show();
					if($('span', $regError).length !== 0){
						$regError.show();
					}
				}, 
				success:function(element){
					if($('span', $regError).length === 1){
						$regError.hide();
					}
					element.remove();
				},
				rules: {
					nickname: {
						required: true,
						duobeiNickname:[4,30],
						remote:{
							url: [duobei.contextPath, '/register/nickname/verify'].join(''),
							type: 'post',
							dataType: 'json',
							data:{
								nickname: $('#nickname').val()
							}
						}
					},
					username: {
						duobeiValidEmail:true,
						required: true,
						rangelength:[6,120],
						remote:{
							url: [duobei.contextPath, '/register/account/verify'].join(''),
							type: 'post',
							dataType: 'json',
							data:{
								email: function() {
									return $('#username').val();
								}
							}
						}
					},
					password:{
						required:true,
						rangelength:[6,16]
					}
				},
				messages: {
					nickname: {
						required: '名字应为2-15个汉字，或4-30个字母',
						duobeiNickname: '名字应为2-15个汉字，或4-30个字母'
					},
					username: {
						duobeiValidEmail: '邮箱的格式为email@example.com',
						required: '邮箱的格式为email@example.com',
						rangelength:'邮箱地址长度为6-120位'
					},
					password: {
						required: '密码应为6-16个字符',
						rangelength:'密码应为6-16个字符'
					}
				}
			});
			
			//头像选择
			$('#choose_avatar').click(function() {
				
				$('.avatar_opr').toggle();
				
				$.ajax({
					async:false,
					url:$(this).attr('href'),
					dataType:'html',
					type:'get',
					beforeSend: function (xhr) {
						 xhr.setRequestHeader("X-Requested-With", "XMLHttpRequest");
					},
					success:function(html){
						$('#avatar_list_content').replaceWith(html);
						
						if($.browser.msie && $.browser.version < 7 && !window.XMLHttpRequest){
							
							$regContent.css('margin-left', 0);
							$regInfo.hide();
							$sysAvatarWrap.show();
						} else {
							
							$regContent.animate({'margin-left': 0}, 1000);
							$regInfo.animate({'opacity': 0}, 500, function() {
								$regInfo.hide();
								$sysAvatarWrap.fadeIn(500);
							});
						}
					}
				});
				return false;
			});
			
			$('#save_avatar').click(function(){
				
				$('.avatar_opr').toggle();
				
				
				if($.browser.msie && $.browser.version < 7 && !window.XMLHttpRequest){
					
					$regContent.css('margin-left', 150);
					$regInfo.show();
					$sysAvatarWrap.hide();
				} else {
					
					$regContent.animate({'margin-left': 150},1000);
					$sysAvatarWrap.fadeOut(500, function() {
						
						$regInfo.show().css('opacity', 0);
						$regInfo.animate({'opacity': 1}, 500);
					});
				}
				
				return false;
			});
			
			$('#avatar_list_content .change a').live('click', function() {
				
				$.ajax({
					async:false,
					url:$(this).attr('href'),
					dataType:'html',
					type:'get',
					beforeSend: function (xhr) {
						 xhr.setRequestHeader("X-Requested-With", "XMLHttpRequest");
					},
					success:function(html){
						$('#avatar_list_content').fadeOut(function(){
							$('#avatar_list_content').replaceWith(html).fadeIn();
						});
					}
				});
				return false;
			});
			
			$('#avatar_list_content img').live('click', function() {
			
				$('img', $regAvatar).attr('src', $(this).attr('src'));
				$('input', $regAvatar).val($(this).next().val());
				$('#avatar_list_content img').removeClass('chosen');
				$(this).addClass('chosen');
			});
			
			$('#show_pwd').click(function(){
				
				var $pwdInput = $(this).prev();
				$('#password').hide();
				var displayText = ($pwdInput.attr('type') === 'password') ? '隐藏密码' : '显示密码',
					p = document.createElement('input'); 
					p.name = 'password';
					p.id = 'password';
					p.value = $pwdInput.val();
					p.placeholder = '密码';
					p.autocomplete = 'off';
					p.type = ($pwdInput.attr('type') === 'password') ? 'text' : 'password';
				
				$('#password').remove();
				this.parentNode.insertBefore(p, this);
				
				$(this).text(displayText);
				
				return false;
			});

		});
	};
})(jQuery);